const EnemySpawner = require("../Enemy/EnemySpawner");
var EnemyController = require("EnemyController");

var EnemyDamager = cc.Class({
    extends: cc.Component,

    properties: {
        damageAmount: 0,

        damageOverTime: false,
        hitWaitTime: 0.5,
        hitCounter: 0,

		lifeTime: 0,

        validHits: cc.Integer,
        isBullet: cc.Boolean, 

        enemiesInRange: {
            default: [],
            type: [EnemyController],
            visible: false,
        }
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        this.hitCount = 0;
    },

	onCollisionEnter (other, self) {
		if (this.damageOverTime == false) {
			if (other.node.group == 'Enemy') {
                if (this.isBullet) {
                    this.hitCount++;
                }
				other.node.getComponent('EnemyController').TakeDamageForRepel(this.damageAmount);

				//this.hitCounter = this.hitWaitTime;
			}
		} else {
			if (other.node.group == 'Enemy') {
				this.enemiesInRange.push(other.node.getComponent("EnemyController"));
			}
		}
	},

	onCollisionExit (other, self) {
		if (this.damageOverTime == true) {
			if (other.node.group == 'Enemy') {
				this.enemiesInRange.splice(this.enemiesInRange.indexOf(other.node.getComponent("EnemyController")), 1);
			}
		}
	},

    update (dt) {
        if (this.isBullet) {
            if (this.hitCount >= this.validHits && this.validHits != -1) {
                this.node.destroy();
            }
        }
        else {
            if (this.damageOverTime == true) {
                this.hitCounter -= dt;

                if (this.hitCounter <= 0) {
                    this.hitCounter = this.hitWaitTime;

                    for (let i = 0; i < this.enemiesInRange.length; i++) {
                        if (this.enemiesInRange[i] != null) {
                            this.enemiesInRange[i].TakeDamage(this.damageAmount);
                        } else {
                            this.enemiesInRange.splice(i, 1);
                            i--;
                        }
                    }
                }
            }
        }
    },

});

module.exports = EnemyDamager;
